package com.dahuyou.tryy.too.simulate.interpreter.instructions.references;

import com.dahuyou.tryy.too.simulate.interpreter.instructions.base.ClassInitLogic;
import com.dahuyou.tryy.too.simulate.interpreter.instructions.base.InstructionIndex16;
import com.dahuyou.tryy.too.simulate.interpreter.instructions.base.MethodInvokeLogic;
import com.dahuyou.tryy.too.simulate.interpreter.runtime.area.Frame;
import com.dahuyou.tryy.too.simulate.interpreter.runtime.area.heap.constantpool.MethodRef;
import com.dahuyou.tryy.too.simulate.interpreter.runtime.area.heap.constantpool.RunTimeConstantPool;
import com.dahuyou.tryy.too.simulate.interpreter.runtime.area.heap.methodarea.Class;
import com.dahuyou.tryy.too.simulate.interpreter.runtime.area.heap.methodarea.Method;

public class INVOKE_STATIC extends InstructionIndex16 {

    @Override
    public void execute(Frame frame) {
        RunTimeConstantPool runTimeConstantPool = frame.method().clazz().constantPool();
        MethodRef methodRef = (MethodRef) runTimeConstantPool.getConstants(this.idx);
        Method resolvedMethod = methodRef.ResolvedMethod();

        if (!resolvedMethod.isStatic()) {
            throw new IncompatibleClassChangeError();
        }

        Class clazz = resolvedMethod.clazz();
        // 确保初始化完成（加载，链接，初始化中的初始化，即类加载的最后一步）
        if (!clazz.initStarted()) {
            frame.revertNextPC();
            ClassInitLogic.initClass(frame.thread(), clazz);
            return;
        }
        // 执行方法（即生成栈帧并压入到线程栈）
        MethodInvokeLogic.invokeMethod(frame, resolvedMethod);
    }
}
